package com.example.screenrecorder;

import android.app.Service;
import android.content.Context;
import android.content.Intent;
import android.graphics.PixelFormat;
import android.os.Build;
import android.os.IBinder;
import android.view.Gravity;
import android.view.LayoutInflater;
import android.view.View;
import android.view.WindowManager;
import android.widget.Button;
import android.widget.TextView;

import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.Locale;
import java.util.Timer;
import java.util.TimerTask;

/**
 * 悬浮窗控制器服务 - 提供录制时的悬浮控制界面
 * 功能特性：
 * - 显示录制状态和时间
 * - 提供停止录制按钮
 * - 实时更新录制时长
 * - 悬浮在屏幕上方，不影响其他应用
 * - 自动定时器更新显示
 * - 支持Android 6.0+的悬浮窗权限
 */
public class FloatingController extends Service {
    
    private WindowManager windowManager;
    private View floatingView;
    private Button btnStop;
    private TextView tvTime;
    private Timer recordingTimer;
    private long startTime;
    
    @Override
    public void onCreate() {
        super.onCreate();
        windowManager = (WindowManager) getSystemService(WINDOW_SERVICE);
        createFloatingView();
    }
    
    private void createFloatingView() {
        LayoutInflater inflater = (LayoutInflater) getSystemService(LAYOUT_INFLATER_SERVICE);
        floatingView = inflater.inflate(R.layout.floating_controller, null);
        
        btnStop = floatingView.findViewById(R.id.btn_floating_stop);
        tvTime = floatingView.findViewById(R.id.tv_floating_time);
        
        btnStop.setOnClickListener(v -> stopRecording());
        
        WindowManager.LayoutParams params = new WindowManager.LayoutParams(
                WindowManager.LayoutParams.WRAP_CONTENT,
                WindowManager.LayoutParams.WRAP_CONTENT,
                Build.VERSION.SDK_INT >= Build.VERSION_CODES.O ?
                        WindowManager.LayoutParams.TYPE_APPLICATION_OVERLAY :
                        WindowManager.LayoutParams.TYPE_PHONE,
                WindowManager.LayoutParams.FLAG_NOT_FOCUSABLE,
                PixelFormat.TRANSLUCENT
        );
        
        params.gravity = Gravity.TOP | Gravity.END;
        params.x = 0;
        params.y = 100;
        
        windowManager.addView(floatingView, params);
        
        startTime = System.currentTimeMillis();
        startTimer();
    }
    
    private void startTimer() {
        recordingTimer = new Timer();
        recordingTimer.scheduleAtFixedRate(new TimerTask() {
            @Override
            public void run() {
                runOnUiThread(() -> {
                    long elapsed = System.currentTimeMillis() - startTime;
                    String timeText = formatTime(elapsed);
                    tvTime.setText(timeText);
                });
            }
        }, 0, 1000);
    }
    
    private void runOnUiThread(Runnable runnable) {
        if (floatingView != null) {
            floatingView.post(runnable);
        }
    }
    
    private String formatTime(long milliseconds) {
        long seconds = milliseconds / 1000;
        long minutes = seconds / 60;
        seconds = seconds % 60;
        return String.format(Locale.getDefault(), "%02d:%02d", minutes, seconds);
    }
    
    private void stopRecording() {
        Intent serviceIntent = new Intent(this, ScreenRecordService.class);
        serviceIntent.setAction(ScreenRecordService.ACTION_STOP_RECORDING);
        startService(serviceIntent);
        
        stopSelf();
    }
    
    @Override
    public void onDestroy() {
        super.onDestroy();
        if (recordingTimer != null) {
            recordingTimer.cancel();
        }
        if (floatingView != null && windowManager != null) {
            windowManager.removeView(floatingView);
        }
    }
    
    @Override
    public IBinder onBind(Intent intent) {
        return null;
    }
}
